import time
from machine import PWM, FPIOA

class LEDController:
    def __init__(self, pin=61, channel=1, freq=2000, initial_duty=50):
        """
        Initialize LED controller with PWM
        
        Args:
            pin: The chip pin number (default: 61)
            channel: PWM channel (default: 1)
            freq: PWM frequency in Hz (default: 2000)
            initial_duty: Initial duty cycle percentage (default: 50)
        """
        # Configure the pin for PWM output
        self.pwm_io = FPIOA()
        self.pwm_io.set_function(pin, FPIOA.PWM1)
        
        # Store channel for later use
        self.channel = channel
        self.pin = pin
        self.freq = freq
        
        # Initialize PWM with parameters
        self.pwm = PWM(channel, freq, initial_duty, enable=True)
        self.current_duty = initial_duty
        
    def set_brightness(self, duty):
        """
        Set LED brightness by adjusting PWM duty cycle
        
        Args:
            duty: Duty cycle percentage (0-100)
        """
        # Ensure duty cycle is within valid range
        duty = max(0, min(100, duty))
        self.pwm.duty(duty)
        self.current_duty = duty
        return duty
        
    def get_brightness(self):
        """
        Get current brightness (duty cycle)
        
        Returns:
            Current duty cycle percentage
        """
        return self.pwm.duty()
        
    def deinit(self):
        """
        Cleanup resources
        """
        # Simply set duty cycle to 0 to turn off the LED
        try:
            self.pwm.duty(0)
        except:
            pass  # Ignore errors if PWM is already disabled or has issues


class TouchSlider:
    def __init__(self, img, x, y, width, height, led_controller, color=(0, 150, 255), bg_color=(50, 50, 50)):
        """
        Create a touch slider for controlling LED brightness
        
        Args:
            img: Display image to draw on
            x, y: Top-left position of the slider
            width, height: Dimensions of the slider
            led_controller: LEDController instance
            color: Slider color (default: blue)
            bg_color: Background color (default: dark gray)
        """
        self.img = img
        self.x = int(x)  # Ensure x is an integer
        self.y = int(y)  # Ensure y is an integer
        self.width = int(width)  # Ensure width is an integer
        self.height = int(height)  # Ensure height is an integer
        self.led_controller = led_controller
        self.color = color
        self.bg_color = bg_color
        self.value = led_controller.get_brightness()
        self.active = False
        self.last_update_time = 0
        
    def draw(self):
        """
        Draw the slider on the image
        """
        # Draw slider background
        self.img.draw_rectangle(self.x, self.y, self.width, self.height, color=self.bg_color, fill=True)
        self.img.draw_rectangle(self.x, self.y, self.width, self.height, color=(255, 255, 255), thickness=2)
        
        # Calculate filled portion based on current value
        fill_width = int(self.width * self.value / 100)
        self.img.draw_rectangle(self.x, self.y, fill_width, self.height, color=self.color, fill=True)
        
        # Draw percentage text - ensure all coordinates are integers
        text_x = int(self.x + self.width + 10)
        text_y = int(self.y + self.height // 2 - 15)
        self.img.draw_string_advanced(text_x, text_y, 30, f"{int(self.value)}%", color=(255, 255, 255), scale=2)
        
        # Draw label - ensure y coordinate is an integer
        label_y = int(self.y - 40)
        self.img.draw_string_advanced(self.x, label_y, 30, "LED亮度", color=(255, 255, 255), scale=2)
        
    def handle_touch(self, touch_point):
        """
        Handle touch input to adjust slider value
        
        Args:
            touch_point: Touch point object with x, y coordinates
            
        Returns:
            True if slider value changed, False otherwise
        """
        # Check if touch is within slider area
        if (self.x <= touch_point.x <= self.x + self.width and
            self.y <= touch_point.y <= self.y + self.height):
            
            # Calculate new value based on touch position
            new_value = ((touch_point.x - self.x) / self.width) * 100
            new_value = max(0, min(100, new_value))
            
            # Update LED brightness if value changed
            if abs(new_value - self.value) > 1:  # Only update if change is significant
                self.value = self.led_controller.set_brightness(new_value)
                return True
                
        return False 